package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.vo.JsonResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.util.List;


/**
 * Author：程Sir
 * Name： demo
 * Content:
 */
//@Controller
@RestController // 等价于 @Controller+@ResponseBody
@RequestMapping("/user")
public class DemoController {

    @RequestMapping("/ajax")
//    @ResponseBody
    public User ajaxa(){
        return new User().setId(1).setPhone("123456879").setUsername("张三");
    }

    @RequestMapping("/hello")
//    @ResponseBody
    public String hello(){
        return "Hello Boot!";
    }

    @Autowired(required = false)
    private UserMapper userMapper;

    @RequestMapping("/register")
//    @ResponseBody
    public JsonResult register(User user){
        User result = userMapper.findOne(user.getUsername());
        if (result == null){
            int row = userMapper.insertOne(user);
            if (row != 1){
                return new JsonResult(400, "用户注册失败！稍后请重试！");
            }
            return new JsonResult(200,"用户注册成功!");
        }else {
            return new JsonResult(400, "用户注册失败！因为用户名已存在！");
        }

    }
    /*
        ***********************************************************
        *                                                         *
        *       学习完redis了之后，再来完成数据查询的缓存功能             *
        *                                                         *
        ***********************************************************
     */

    @RequestMapping("/findUsers.do")
//    @ResponseBody
    public JsonResult findAll(){
        // 创建jedis对象
        Jedis jedis = new Jedis();
        // 获取缓存的数据 1. 先从缓存中找，有没有
        String json =  jedis.get("users");

        //如果缓存中不存在，则从数据库mysql中查询数据
        if (json == null || json.length()==0){

            List<User> users = userMapper.findAll();
            // 将对象进行json转换
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                json= objectMapper.writeValueAsString(users);
                System.out.println("对象转换为json： " + json);

                // 需要在redis中缓存一份，供以后查询使用！
                jedis.set("users",json);
                System.out.println("数据是从mysql数据库中获取的！");
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }else{
            System.out.println("数据是从redis数据库中获取的！");
        }

        return new JsonResult(200,"用户数据查询成功！",json);
    }

}
